package com.csdj.t309.common;

import com.csdj.t309.entity.TAddress;
import org.springframework.format.Formatter;
import org.springframework.util.StringUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.Locale;

public class TAddressFormatter implements Formatter<TAddress> {
    @Override
    public TAddress parse(String text, Locale locale) throws ParseException {
        TAddress address = new TAddress();
        Class<? extends TAddress> aClass = address.getClass();
        String[] splits = text.split(",");
        for(String split: splits){
            String[] kvs = split.split(":");
            try {
                Method method = aClass.getDeclaredMethod("set" + StringUtils.capitalize(kvs[0]),String.class);
                method.invoke(address,kvs[1]);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return address;
    }

    @Override
    public String print(TAddress object, Locale locale) {
        return object.toString();
    }
}
